#include "rtphandler.h"

#include <QDebug>
#include <cstdlib>
#include <ctime>
#include <QDataStream>


RTPHandler::RTPHandler(const QHostAddress &remoteAddress, quint16 remotePort,
                       quint16 localPort, QObject *parent)
    : QObject(parent),remoteAddress(remoteAddress), remotePort(remotePort),
    sequenceNumber(0), timestamp(0)
{
    std::srand(std::time(nullptr)); // Use current time as seed for random generator
    ssrc = std::rand(); // Generate a random SSRC

    udpSocket = new QUdpSocket(this);
    udpSocket->bind(QHostAddress::Any, localPort);
    connect(udpSocket, &QUdpSocket::readyRead, this, &RTPHandler::processPendingDatagrams);


}

RTPHandler::~RTPHandler()
{
    delete udpSocket;
}

void RTPHandler::sendRTPPacket(const QByteArray &payload)
{
    RTPHeader header;
    header.version = 2;
    header.padding = 0;
    header.extension = 0;
    header.csrcCount = 0;
    header.marker = 0;
    header.payloadType = 0; // Payload type 0 for G.711 A-law
    header.sequenceNumber = ++sequenceNumber;
    header.timestamp = timestamp;
    header.ssrc = ssrc;

    QByteArray packet;
    QDataStream stream(&packet, QIODevice::WriteOnly);
    stream.writeRawData(reinterpret_cast<char*>(&header), sizeof(RTPHeader));
    stream.writeRawData(payload.constData(), payload.size());

    udpSocket->writeDatagram(packet, remoteAddress, remotePort);

    timestamp += payload.size(); // Adjust according to your sample rate and sample size
}

void RTPHandler::processPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams()) {
       QByteArray datagram;
       datagram.resize(udpSocket->pendingDatagramSize());
       udpSocket->readDatagram(datagram.data(), datagram.size());

       if (datagram.size() < static_cast<int>(sizeof(RTPHeader))) {
           qWarning() << "Received too short RTP packet";
           continue;
       }

       RTPHeader *header = reinterpret_cast<RTPHeader*>(datagram.data());
       if (header->version != 2) {
           qWarning() << "Received invalid RTP version";
           continue;
       }

       QByteArray payload = datagram.mid(sizeof(RTPHeader));
       emit rtpPacketReceived(payload);

    }
}
